package com.cxlin.cwanandroid.ui.blog.viewmodel

import androidx.lifecycle.viewModelScope
import com.cxlin.base.BaseViewModel
import com.cxlin.base.model.api.Result
import com.cxlin.base.mvi.UiEvent
import com.cxlin.base.mvi.UiIntent
import com.cxlin.base.mvi.UiState
import com.cxlin.cwanandroid.model.bean.SystemParent
import com.cxlin.cwanandroid.model.repository.ProjectRepository
import com.cxlin.cwanandroid.ui.login.viewmodel.LoginViewModel
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch

/**
 *
 * @Author: chenxunlin
 * @Date: 2024/4/30 9:34
 */
class TabBlogViewModel(private val repository: ProjectRepository) : BaseViewModel() {

    sealed class TabBlogUiState : UiState {
        object Idel : TabBlogUiState()
        data class BlogTypes(val result: List<SystemParent>) : TabBlogUiState()
    }

    sealed class TabBlogEvent : UiEvent {
        class ToastEvent(val message: String, val short: Boolean = false) : TabBlogEvent()
    }

    sealed class TabBLogUiIntent : UiIntent {
        class GetBlogType : TabBLogUiIntent()
    }

    override fun handleIntent(intent: UiIntent) {
        when (intent) {
            is TabBLogUiIntent.GetBlogType -> {
                viewModelScope.launch {
                    kotlin.runCatching {
                        val result = repository.getBlog()
                        if (result is Result.Success) {
                            mUiStateFlow.update { TabBlogUiState.BlogTypes(result.data) }
                        } else if (result is Result.Error) {
                            mEffectFlow.emit(LoginViewModel.LoginEvent.ToastEvent(result.exception.message ?: "网络异常", true))
                        }
                    }
                }
            }
        }
    }

    override fun createInitState(): UiState {
        return TabBlogUiState.Idel
    }
}